﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

//【1】host默认就为我们配置了很多服务如：Configuration读取本地appsettinngs.json
// 如果json文件名称不是默认的当然可以显式配置
//自动初始化IOC容器serviceProvide
using IHost host = Host.CreateDefaultBuilder(args)
    .UseEnvironment("Development")
    .ConfigureHostConfiguration(builder =>
    {
        builder.AddJsonFile("appsettings.Decelopment.json", optional: true, reloadOnChange: true);
        builder.AddCommandLine(args);
        builder.AddEnvironmentVariables();
        builder.AddUserSecrets<Program>();
    })
    .ConfigureServices(builder =>
    {
        // builder.AddTransient<MyService>();
        builder.AddHostedService<MyService>();
    })
    .ConfigureLogging(builder =>
    {
        //如果不配置ConfigureLogging的话，host默认会从appSettings.json获取值进行设置
        builder.SetMinimumLevel(LogLevel.Trace);
    })
    .Build();
// host.run是阻塞方法;host.start是非阻塞，其后的代码会继续执行
// host.Run();
host.Start();

// 【3】AddHostedService<MyService>注册的后台服务不需要手动获取运行，会自动执行ExecuteAsync
// var myService = host.Services.GetService<MyService>();
// myService?.Dowork();

//等待窗口叉掉或者输入CTRL + C 关掉服务
host.WaitForShutdown();

//【2】对于在后台运行的服务，规范的写法是继承BackgroundService
//注册服务的时候对应变成AddHostedService
class MyService : BackgroundService
{
    private readonly IHostEnvironment _hostEnvironment;
    private readonly ILogger<MyService> _logger;

    private readonly IConfiguration _configuration;

    // 这些服务host已经在后台默认帮我们创建了(IOC、config、log)
    public MyService(IHostEnvironment hostEnvironment, ILogger<MyService> logger, IConfiguration configuration)
    {
        _hostEnvironment = hostEnvironment;
        _logger = logger;
        _configuration = configuration;
    }

    public void Dowork()
    {
        //log等级 Information > Debug > Trace
        _logger.LogInformation("Application Name: {0}", _hostEnvironment.ApplicationName);
        _logger.LogInformation("Environment: {0}", _hostEnvironment.EnvironmentName);
        _logger.LogInformation("ContentRootPath: {0}", _hostEnvironment.ContentRootPath);
        _logger.LogDebug("logLevel: {0}", _configuration["Logging:LogLevel:Default"]);
        _logger.LogDebug("logInterval: {0}", _configuration["UserSettings:LogInterval"]);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await Task.Run(Dowork, stoppingToken);
    }
}
// class MyService
// {
//     private readonly IHostEnvironment _hostEnvironment;
//     private readonly ILogger<MyService> _logger;
//
//     public MyService(IHostEnvironment hostEnvironment, ILogger<MyService> logger)
//     {
//         _hostEnvironment = hostEnvironment;
//         _logger = logger;
//     }
//
//     public void Dowork()
//     {
//         // HostConsoleApp;Production;\bin\Debug\net8.0-windows
//         // Console.WriteLine($"Application Name: {_hostEnvironment.ApplicationName}");
//         // Console.WriteLine($"Environment: {_hostEnvironment.EnvironmentName}");
//         // Console.WriteLine($"ContentRootPath: {_hostEnvironment.ContentRootPath}");
//         // 使用Microst提供的Logger包在控制台输出信息会带特殊的样式标识
//         _logger.LogInformation("Application Name: {0}", _hostEnvironment.ApplicationName);
//         _logger.LogInformation("Environment: {0}", _hostEnvironment.EnvironmentName);
//         _logger.LogInformation("ContentRootPath: {0}", _hostEnvironment.ContentRootPath);
//     }
// }